<template>
  <div class='tinymce'>
    <h1>
      <el-row>
        <el-col :span="5">
          <span v-if="dataArtice">修改文章</span>
          <span v-else>添加文章</span>
          <el-button class="addBtn" @click="goBack">返回</el-button>
        </el-col>
        <el-col :span="19" style="text-align:right">
           <el-button v-if="article" type="primary" @click="submitArticle('formAling')">修改文章</el-button>
           <el-button v-else type="success" @click="submitArticle('formAling')">保存</el-button>
        </el-col>
      </el-row>
    </h1>
    <div>
      <el-form :inline="true"  :rules="form1" ref="form1" :model="form1">
        <el-form-item label="分类">
          <el-select  v-model="form1.value" placeholder="请选择" style="width:120px">
          <el-option
            v-for="item in form1.options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form1.line" placeholder="请选择状态" style="width:120px">
            <el-option v-for="item in form1.lines" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布者ID">
          <el-select v-model="form1.hlpe" placeholder="请选择ID" style="width:120px">
           <el-option v-for="item in form1.hlpes" :key="item.userId" :label="item.userNick" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
         <el-form-item  prop="type">
            <el-checkbox v-model="form1.type"  label="首页推荐文章" name="type"></el-checkbox>
        </el-form-item>
        <el-form-item label="点击量" v-if="dataArtice">
          <el-input v-model="form1.page_view" style="width:80px" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="点赞数" v-if="dataArtice">
          <el-input v-model="form1.stars" style="width:80px" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
     <el-form  label-width="80px" :rules="aling" ref="formAling" :model="formLabelAlign">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="formLabelAlign.title"></el-input>
        </el-form-item>
      </el-form>
      <el-row>
        <el-col :span="12">
        
        <el-form :inline="true"  :rules="form2" ref="form2" :model="form2">
          <el-form-item label="文章描述" prop="desc">
            <el-input style="width:300px;height:146px" type="textarea" v-model="form2.desc"></el-input>
          </el-form-item>
         </el-form>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="18">
             <span style="font-weight:normal;font-size:14px">封面图：</span>
              <el-upload
                style="display:inline-block"
                :action="action"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-success="handleOK"
                :data="postData"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-col>
            <el-col :span="6">
              <img :src="articleThum" style="width:120px;height:150px"/>
            </el-col>
          </el-row>
        </el-col>

      </el-row>
      <el-row>
        <h4 style="margin:0 0 10px 0">编写文章内容：</h4>
        <div style="padding-left:20px">
          <el-col v-for="(item,index) in articleContent" :key="item.key">
              <p style="margin-top:0">图{{index+1}}:<el-button class="addBtn" @click.prevent="removeDomain(item)" type="danger" style="margin-left:50px">删除</el-button></p>
              <el-form  :model="item" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
              <el-form-item label="内容图片">
                <el-row>
                <el-col :span="10">
                <span @click="checkItemImg(index)">        
                  <el-upload
                    style="display:inline-block"
                    :action="action"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-success="handleOK"
                    :data="postData"
                    :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </span>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
                </el-col>
                <el-col :span="5">
                  <img :src="item.imageUrl" style="width:120px;height:150px;maring-left:50px" />
                </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="图片描述">        
                <el-input v-model="item.imageDesc"></el-input>
              </el-form-item>
              <el-form-item  label="文字内容">
                <el-input type="textarea" v-model="item.content"></el-input>
              </el-form-item>
              </el-form>
          </el-col>

          <el-button style="margin-left:150px" type="primary" @click="addDomain">添加内容</el-button>
          <el-button style="margin-left:240px" type="success" @click="submitArticle('formAling')">保存文章</el-button>
        </div>
      </el-row>
    
    </div>

  </div>
</template>

<script>
import {mapActions,mapMutations,mapGetters,mapState} from 'vuex'
import Http from '@/Http/Http'

export default {
  name: 'tinymce',
  props:['dataArtice'],
  data () {
    const title = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请输入标题'))
      } else {
        callback()
      }
    }
    return {
      articleContent:[
        {
          content:'',
          imageDesc:'',
          imageUrl:'',
        }
      ],
      imgIndex:'',
      imgUrl:'', // 
      postData:{
        token:'',
      },
      articleThum:'',// 封面图
      tokenimgUrl:'', //域名地址
      form2:{
        desc:'',
      },
      dialogImageUrl: '',
      dialogVisible: false,
       form1:{
        page_view:0,
        stars:0,
        hlpe:10001,
        line:1,
        value:0,
        hlpes:[
          {value:10001,label:'牙套小助手'},
          {value:10002,label:'口腔小助手'}
        ],
        lines:[
          {value:1,label:'上线'},
          {value:2,label:'下线'}
        ],
        type:false,

        options:[{
          value:0,
          label:'全部'
        },{
          value:1,
          label:'牙齿矫正'
        },{
          value:2,
          label:'口腔健康'
        },{
          value:3,
          label:'儿童口腔'
        },{
          value:4,
          label:'种植牙'
        }],
      },
      formLabelAlign:{
        title:'',
        
      },
      aling:{
        title:[
          {validator:title,trigger:'blur'}
        ]
      },
      coentSta:false
    }
  },

  computed: {
    ...mapState(['article'])  
  },
  mounted () {
    
  },
  created() {
    this.getToken()
  },
  methods:{
    getToken() {
      if (this.dataArtice) {
        this.form1.value = this.dataArtice.type?this.dataArtice.type:0  //类型   stars
        this.form1.page_view  = this.dataArtice.countRead?this.dataArtice.countRead:0 
        this.form1.stars = this.dataArtice.countLike?this.dataArtice.countLike:0 
        if(this.dataArtice.isRecommend){
          this.form1.type = true
        } else {
          this.form1.type = false
        }   // 推荐 
        this.form1.hlpe = this.dataArtice.articleUser.userId //发布者id 
        // this.form1.hlpe = this.dataArtice.articleUserid?this.dataArtice.articleUserid:10001 //发布者id 
        this.form1.line = this.dataArtice.articleStatus //状态
        this.formLabelAlign.title = this.dataArtice.articleTitle //标题
        this.articleThum = this.dataArtice.articleThum //封面图
        if(this.dataArtice.contentItemList.length>0){
          this.articleContent = this.dataArtice.contentItemList
        }
      }
      Http.getCuser({})
      .then( res => {
        this.form1.hlpes  = res.data.data;
       
      })
      .catch( error => {
        
      })


      Http.QiniuToken({})
      .then( res => {
        this.postData.token = res.data.data.uptoken;
        this.tokenimgUrl = res.data.data.domain
      })
      .catch( error => {
        
      })
    },
    handleRemove(file, fileList) {
      
    },
    handlePictureCardPreview(event, file, fileList) {
    },
    handleOK(responed) {
      if(this.imgIndex !== ''){
        this.articleContent[this.imgIndex].imageUrl = `http://${this.tokenimgUrl}/${responed.key}`;
        this.imgIndex = '';

      } else {
        this.articleThum = `http://${this.tokenimgUrl}/${responed.key}`
      }
    },
    checkItemImg(val) {
      this.imgIndex = val;
    },
    submitArticle(val) {
      this.$refs[val].validate((valid) => {
        const obj = [];
        if (valid) {
          if (!this.articleThum) {
            this.$message.error('请上传文章封面图')
            return
          }
          this.articleContent.forEach( item => {
            if(item.imageUrl || item.content){
              obj.push(item)
            } else {
              this.coentSta = true
            }
          })
          if(obj.length == 0 && this.coentSta){
              this.$message.error('请填写内容')
          }
         
          const isRe = this.form1.type?1:0;
          const jsonobj = JSON.stringify(obj);
          const reg = jsonobj.replace(/\"/g, '\"');

          const param = {
            "articleTitle":this.formLabelAlign.title,  //文章标题
            "articleThum":this.articleThum,  //封面
            "articleStatus":this.form1.line,  //上线状态 
            "articleContent":reg, // 文章内容  实体列表 
            "articleUserid":this.form1.hlpe,
           
            "isRecommend":isRe, //推荐
            "topic":{
              "id":this.form1.value //分类 id 
            }
          }

          if (this.dataArtice) {
            param.articleId = this.dataArtice.articleId
            param.countLike = this.form1.page_view;
            param.countShare = this.form1.stars;
            this.postEditAriticeFun(param)
          } else {
            this.addAriticeFun(param)
          }
          
        } else {
          this.$message.error('请填写标题')
        }
      })
      
    },
    addAriticeFun(param) {
      Http.addAritice(param)
        .then( res => {
          if( res.data.code == 200 ){
            this.$message.success('文章发布成功')
            this.goBack()         
          } else if(res.data.code == -1003) {
            this.$message.error(`请求失败原因：${res.data.message}`)
            this.$router.push('/')
          }
        })
        .catch( error => {
          this.$message.error('服务器请求失败')
        })
    },
    postEditAriticeFun(param) {
      
      Http.postEditAritice(param)
      .then( res => {
        if( res.data.code == 200 ){
          this.$message.success('文章修改成功')
          this.goBack()         
        } else if(res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          this.$router.push('/')
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
      })
    },
    goBack(){
      this.$emit('getlist')
    },
    addDomain() {
      this.articleContent.push({
        content:'',
        imageDesc:'',
        imageUrl:'',
        key: Date.now()
      });
    },
     removeDomain(item) {
      var index = this.articleContent.indexOf(item)
      if (index !== -1) {
        this.articleContent.splice(index, 1)
      }
    },
  }
}
</script>
<style>
.el-textarea__inner{
  height:146px
}
</style>
